package com.duolaibei.business.utils;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import com.duolaibei.business.utils.log.LogDebug;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class PrintUtils {

//    /**
//     * 打印小票
//     */
//    private void printData() {
//        if (BluetoothUtil.connectBlueTooth(getThis())) {
//            PrintUtils.setOutputStream(BluetoothUtil.getOutputStream());
//            PrintUtils.selectCommand(PrintUtils.RESET);
//            PrintUtils.selectCommand(PrintUtils.LINE_SPACING_DEFAULT);
//            PrintUtils.selectCommand(PrintUtils.ALIGN_CENTER);
//            PrintUtils.printText("美食餐厅\n\n");
//            PrintUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT_WIDTH);
//            PrintUtils.printText("桌号：1号桌\n\n");
//            PrintUtils.selectCommand(PrintUtils.NORMAL);
//            PrintUtils.selectCommand(PrintUtils.ALIGN_LEFT);
//            PrintUtils.printText(PrintUtils.printTwoData("订单编号", "201507161515\n"));
//            PrintUtils.printText(PrintUtils.printTwoData("点菜时间", "2016-02-16 10:46\n"));
//            PrintUtils.printText(PrintUtils.printTwoData("上菜时间", "2016-02-16 11:46\n"));
//            PrintUtils.printText(PrintUtils.printTwoData("人数：2人", "收银员：张三\n"));
//            PrintUtils.printText("--------------------------------\n");
//            PrintUtils.selectCommand(PrintUtils.BOLD);
//            PrintUtils.printText(PrintUtils.printThreeData("项目", "数量", "金额\n"));
//            PrintUtils.printText("--------------------------------\n");
//            PrintUtils.selectCommand(PrintUtils.BOLD_CANCEL);
//            PrintUtils.printText(PrintUtils.printThreeData("面", "1", "0.00\n"));
//            PrintUtils.printText(PrintUtils.printThreeData("米饭", "1", "6.00\n"));
//            PrintUtils.printText(PrintUtils.printThreeData("铁板烧", "1", "26.00\n"));
//            PrintUtils.printText(PrintUtils.printThreeData("一个测试", "1", "226.00\n"));
//            PrintUtils.printText(PrintUtils.printThreeData("牛肉面啊啊", "1", "2226.00\n"));
//            PrintUtils.printText(PrintUtils.printThreeData("牛肉面啊啊啊牛肉面啊啊啊", "888", "98886.00\n"));
//            PrintUtils.printText("--------------------------------\n");
//            PrintUtils.printText(PrintUtils.printTwoData("合计", "53.50\n"));
//            PrintUtils.printText(PrintUtils.printTwoData("抹零", "3.50\n"));
//            PrintUtils.printText("--------------------------------\n");
//            PrintUtils.printText(PrintUtils.printTwoData("应收", "50.00\n"));
//            PrintUtils.printText("--------------------------------\n");
//            PrintUtils.selectCommand(PrintUtils.ALIGN_LEFT);
//            PrintUtils.printText("备注：不要辣、不要香菜");
//            PrintUtils.printText("\n\n\n\n\n");
//        }
//    }
    /**
     * 打印纸一行最大的字节
     */
    private static final int LINE_BYTE_SIZE = 32;

    private static final int LEFT_LENGTH = 20;

    private static final int RIGHT_LENGTH = 12;

    /**
     * 左侧汉字最多显示几个文字
     */
    private static final int LEFT_TEXT_MAX_LENGTH = 8;

    /**
     * 小票打印菜品的名称，上限调到8个字
     */
    public static final int MEAL_NAME_MAX_LENGTH = 8;

    private static OutputStream outputStream = null;

    public static OutputStream getOutputStream() {
        return outputStream;
    }

    public static void setOutputStream(OutputStream outputStream) {
        PrintUtils.outputStream = outputStream;
    }


    /**
     * 打印一维条形码
     */
    public static byte[] getPrintBarCode(String data, int symbology, int height, int width, int textposition) {
        if (symbology < 0 || symbology > 8) {
            return new byte[]{0x0A};
        }

        if (width < 2 || width > 6) {
            width = 2;
        }

        if (textposition < 0 || textposition > 3) {
            textposition = 0;
        }

        if (height < 1 || height > 255) {
            height = 162;
        }
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try {
            buffer.write(new byte[]{0x1D, 0x66, 0x01, 0x1D, 0x48, (byte) textposition,
                    0x1D, 0x77, (byte) width, 0x1D, 0x68, (byte) height, 0x0A});

            byte[] barcode = data.getBytes("GB18030");

            if (symbology == 8) {
                buffer.write(new byte[]{0x1D, 0x6B, 0x49, (byte) (barcode.length+2), 0x7B, 0x42});
            } else {
                buffer.write(new byte[]{0x1D, 0x6B, (byte) (symbology + 0x41), (byte) barcode.length});
            }
            buffer.write(barcode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toByteArray();
    }

    /**
     * 打印文字
     *
     * @param text 要打印的文字
     */
    public static void printText(String text) {
        try {
            byte[] data = text.getBytes("gbk");
            outputStream.write(data, 0, data.length);
            outputStream.flush();
        } catch (IOException e) {
            //Toast.makeText(this.context, "发送失败！", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    /**
     * 打印bitmap
     *
     * @param bitmap 图片数据
     */
    public static void printBitmap(byte[] bitmap) {
        LogDebug.d("------------bitmap------------" + bitmap.length);
        try {
            // 发送打印图片前导指令
            byte[] start = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B,
                    0x40, 0x1B, 0x33, 0x00};
            outputStream.write(start, 0, start.length);//开始
            outputStream.flush();

            outputStream.write(bitmap, 0, bitmap.length);//图片
            outputStream.flush();

            byte[] end = {0x1d, 0x4c, 0x1f, 0x00};//结束
            outputStream.write(end, 0, end.length);
            outputStream.flush();

            outputStream.write(RESET);//重置
            outputStream.flush();
            outputStream.write(LINE_SPACING_DEFAULT);//空格
            outputStream.flush();
            outputStream.write(ALIGN_LEFT);//左对齐
            outputStream.flush();

        } catch (IOException e) {
            //Toast.makeText(this.context, "发送失败！", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    /**
     * 设置打印格式
     *
     * @param command 格式指令
     */
    public static void selectCommand(byte[] command) {
        try {
            outputStream.write(command);
            outputStream.flush();
        } catch (IOException e) {
            //Toast.makeText(this.context, "发送失败！", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    /**
     * 复位打印机
     */
    public static final byte[] RESET = {0x1b, 0x40};

    /**
     * 左对齐
     */
    public static final byte[] ALIGN_LEFT = {0x1b, 0x61, 0x00};

    /**
     * 中间对齐
     */
    public static final byte[] ALIGN_CENTER = {0x1b, 0x61, 0x01};

    /**
     * 右对齐
     */
    public static final byte[] ALIGN_RIGHT = {0x1b, 0x61, 0x02};

    /**
     * 选择加粗模式
     */
    public static final byte[] BOLD = {0x1b, 0x45, 0x01};

    /**
     * 取消加粗模式
     */
    public static final byte[] BOLD_CANCEL = {0x1b, 0x45, 0x00};

    /**
     * 宽高加倍
     */
    public static final byte[] DOUBLE_HEIGHT_WIDTH = {0x1d, 0x21, 0x11};

    /**
     * 宽加倍
     */
    public static final byte[] DOUBLE_WIDTH = {0x1d, 0x21, 0x10};

    /**
     * 高加倍
     */
    public static final byte[] DOUBLE_HEIGHT = {0x1d, 0x21, 0x01};

    /**
     * 字体不放大
     */
    public static final byte[] NORMAL = {0x1d, 0x21, 0x00};

    /**
     * 设置默认行间距
     */
    public static final byte[] LINE_SPACING_DEFAULT = {0x1b, 0x32};

    /**
     * 设置行间距
     */
//	public static final byte[] LINE_SPACING = {0x1b, 0x32};//{0x1b, 0x33, 0x14};  // 20的行间距（0，255）


//	final byte[][] byteCommands = {
//			{ 0x1b, 0x61, 0x00 }, // 左对齐
//			{ 0x1b, 0x61, 0x01 }, // 中间对齐
//			{ 0x1b, 0x61, 0x02 }, // 右对齐
//			{ 0x1b, 0x40 },// 复位打印机
//			{ 0x1b, 0x4d, 0x00 },// 标准ASCII字体
//			{ 0x1b, 0x4d, 0x01 },// 压缩ASCII字体
//			{ 0x1d, 0x21, 0x00 },// 字体不放大
//			{ 0x1d, 0x21, 0x11 },// 宽高加倍
//			{ 0x1b, 0x45, 0x00 },// 取消加粗模式
//			{ 0x1b, 0x45, 0x01 },// 选择加粗模式
//			{ 0x1b, 0x7b, 0x00 },// 取消倒置打印
//			{ 0x1b, 0x7b, 0x01 },// 选择倒置打印
//			{ 0x1d, 0x42, 0x00 },// 取消黑白反显
//			{ 0x1d, 0x42, 0x01 },// 选择黑白反显
//			{ 0x1b, 0x56, 0x00 },// 取消顺时针旋转90°
//			{ 0x1b, 0x56, 0x01 },// 选择顺时针旋转90°
//	};

    /**
     * 打印两列
     *
     * @param leftText  左侧文字
     * @param rightText 右侧文字
     * @return
     */
    @SuppressLint("NewApi")
    public static String printTwoData(String leftText, String rightText) {
        StringBuilder sb = new StringBuilder();
        int leftTextLength = getBytesLength(leftText);
        int rightTextLength = getBytesLength(rightText);
        sb.append(leftText);

        // 计算两侧文字中间的空格
        int marginBetweenMiddleAndRight = LINE_BYTE_SIZE - leftTextLength - rightTextLength;

        for (int i = 0; i < marginBetweenMiddleAndRight; i++) {
            sb.append(" ");
        }
        sb.append(rightText);
        return sb.toString();
    }

    /**
     * 打印三列
     *
     * @param leftText   左侧文字
     * @param middleText 中间文字
     * @param rightText  右侧文字
     * @return
     */
    @SuppressLint("NewApi")
    public static String printThreeData(String leftText, String middleText, String rightText) {
        StringBuilder sb = new StringBuilder();
        // 左边最多显示 LEFT_TEXT_MAX_LENGTH 个汉字 + 两个点
        if (leftText.length() > LEFT_TEXT_MAX_LENGTH) {
            leftText = leftText.substring(0, LEFT_TEXT_MAX_LENGTH) + "..";
        }
        int leftTextLength = getBytesLength(leftText);
        int middleTextLength = getBytesLength(middleText);
        int rightTextLength = getBytesLength(rightText);

        sb.append(leftText);
        // 计算左侧文字和中间文字的空格长度
        int marginBetweenLeftAndMiddle = LEFT_LENGTH - leftTextLength - middleTextLength / 2;

        for (int i = 0; i < marginBetweenLeftAndMiddle; i++) {
            sb.append(" ");
        }
        sb.append(middleText);

        // 计算右侧文字和中间文字的空格长度
        int marginBetweenMiddleAndRight = RIGHT_LENGTH - middleTextLength / 2 - rightTextLength;

        for (int i = 0; i < marginBetweenMiddleAndRight; i++) {
            sb.append(" ");
        }

        // 打印的时候发现，最右边的文字总是偏右一个字符，所以需要删除一个空格
        sb.delete(sb.length() - 1, sb.length()).append(rightText);
        return sb.toString();
    }

    /**
     * 获取数据长度
     *
     * @param msg
     * @return
     */
    @SuppressLint("NewApi")
    private static int getBytesLength(String msg) {
        return msg.getBytes(Charset.forName("GB2312")).length;
    }

    /**
     * 格式化菜品名称，最多显示MEAL_NAME_MAX_LENGTH个数
     *
     * @param name
     * @return
     */
    public static String formatMealName(String name) {
        if (TextUtils.isEmpty(name)) {
            return name;
        }
        if (name.length() > MEAL_NAME_MAX_LENGTH) {
            return name.substring(0, 8) + "..";
        }
        return name;
    }

}